package com.huimingpay.merchant.controller;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.huimingpay.common.domain.BusinessException;
import com.huimingpay.common.domain.CommonErrorCode;
import com.huimingpay.common.util.PhoneUtil;
import com.huimingpay.common.util.RandomUuidUtil;
import com.huimingpay.common.util.StringUtil;
import com.huimingpay.merchant.api.MerchantService;
import com.huimingpay.merchant.dto.MerchantDTO;
import com.huimingpay.merchant.common.utils.SecurityUtil;
import com.huimingpay.merchant.convert.MerchantDetailConvert;
import com.huimingpay.merchant.convert.MerchantVOConvert;
import com.huimingpay.merchant.service.FileService;
import com.huimingpay.merchant.service.SmsService;
import com.huimingpay.merchant.vo.MerchantDetailVO;
import com.huimingpay.merchant.vo.MerchantRegisterVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

@RestController
@Api(value = "商户平台应用接口", tags = {"商户平台应用接口"}, description = "商户平台应用接口")
@Slf4j
public class MerchantController {
    @Reference(check = false) // 启动时不检查服务提供方
    MerchantService merchantService; //注入Dubbo调用的服务

    // 注入验证码服务接口
    @Resource
    SmsService smsService;

    //文件上传
    @Resource
    FileService fileService;

    /**
     * 查询商户信息
     *
     * @param id 商户id
     * @return 商户信息
     */
    @GetMapping("/get/{id}")
    // 定义API操作，描述为“根据Id查询商户信息”
    @ApiOperation(value = "根据Id查询商户信息")
    public MerchantDTO getMerchant(@PathVariable("id") Long id) {
        // 调用merchantService的queryMerchantById方法，传入参数id进行查询
        MerchantDTO merchant = merchantService.queryMerchantById(id);
        // 返回查询到的商户信息
        return merchant;
    }


    /**
     * 获取短信验证码
     *
     * @param phone 手机号
     * @return 验证码key, 据此获取验证码
     */
    @GetMapping("/smsKey")
    @ApiOperation(value = "获取短信验证码")
    @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query")
    public JsonElement getSMSKey(@RequestParam("phone") String phone) {
        //手机号非空校验
        if (StringUtil.isBlank(phone)) {
            throw new BusinessException(CommonErrorCode.E_100112);
        }
        //校验手机号的合法性
        if (!PhoneUtil.isMatches(phone)) {
            throw new BusinessException(CommonErrorCode.E_100109);
        }

        log.info("向手机号:{}发送短信验证码", phone);
        String sms = smsService.sendSms(phone);
        String jsonSms = "{\"key\":" + "\"" + sms + "\"" + "}";
        //以json格式返回验证码key
        JsonElement parse = new JsonParser().parse(jsonSms);
        return parse;
    }


    @ApiOperation(value = "商户注册")
    @ApiImplicitParam(name = "registerMerchant", value = "商户注册信息", required = true
            , dataType = "MerchantRegisterVo", paramType = "body")
    @PostMapping("/register")
    public MerchantRegisterVo registerMechant(@RequestBody MerchantRegisterVo registerMerchant) {
        //制造错误
        //int i = 1 / 0;
        // controller层校验
        // 商户注册信息非空校验
        if (registerMerchant == null) {
            throw new BusinessException(CommonErrorCode.E_100108);
        }
        //手机号非空校验
        if (StringUtil.isBlank(registerMerchant.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100112);
        }
        //校验手机号的合法性
        if (!PhoneUtil.isMatches(registerMerchant.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100109);
        }
        //联系人非空校验
        if (StringUtil.isBlank(registerMerchant.getUsername())) {
            throw new BusinessException(CommonErrorCode.E_100110);
        }
        //密码非空校验
        if (StringUtil.isBlank(registerMerchant.getPassword())) {
            throw new BusinessException(CommonErrorCode.E_100111);
        }
        //验证码非空校验
        if (StringUtil.isBlank(registerMerchant.getVerifyCode()) ||
                StringUtil.isBlank(registerMerchant.getVerifyKey())) {
            throw new BusinessException(CommonErrorCode.E_100103);
        }

        //校验验证码
        smsService.checkVerifyCode(registerMerchant.getVerifyKey(), registerMerchant.getVerifyCode());

        //注册商户
        MerchantDTO merchantDTO = MerchantVOConvert.INSTANCE.VOToDTO(registerMerchant);

        merchantService.createMerchant(merchantDTO);

        //返回商户信息
        return registerMerchant;
    }


    //文件上传：使用多功能表单
    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        String originalFilename = file.getOriginalFilename(); //获取源文件名称
        // 获取文件后缀
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID生成文件名称，防止文件名重复
        String fileName = RandomUuidUtil.getUUID() + extName;
        // 需根据业务场景给文件适当分层
        String filePath = "merchants/images/" + fileName;
        // 文件上传
        String upLoad = null;
        try {
            upLoad = fileService.upload(filePath, file.getInputStream());
        } catch (IOException e) {
            throw new BusinessException(CommonErrorCode.E_100106);
        }
        return upLoad;
    }


    @ApiOperation(value = "资质申请")
    @PostMapping("/qual")
    @ApiImplicitParam(name = "merchantInfo", value = "资质申请信息", required = true,
            dataType = "MerchantDetailVO", paramType = "body")
    public String applyQual(@RequestBody MerchantDetailVO merchantInfo) {
        //解析token 获取商户id
        Long merchantId = SecurityUtil.getMerchantId();

        // VO转DTO
        MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCE.VoToDto(merchantInfo);

        // 调用MerchantService
        merchantService.applyMerchant(merchantId, merchantDTO);

        // 返回成功
        return "success";
    }


}
